package com.zhuss.util.bean;

import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;


public class ReflectUtil {
			
	@SuppressWarnings("rawtypes")
	public static Object getObject(Object dest, Map<String, Object> addProperties) {
	    PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
	    
	    PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
	    Map<String, Class> propertyMap = Maps.newHashMap();
	    for (PropertyDescriptor d : descriptors) {
	        if (!"class".equalsIgnoreCase(d.getName())) {
	            propertyMap.put(d.getName(), d.getPropertyType());
	        }
	    }
	    addProperties.forEach((k, v) -> {
	    	String sclass = v.getClass().toString();
	    	if(sclass.equals("class java.util.Date")) {//对日期进行处理
	    		propertyMap.put(k, Long.class);
	    	}else {
	    		propertyMap.put(k, v.getClass());
	    	}
	    	
	    });
	    DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
	    propertyMap.forEach((k, v) -> {
	        try {
	            if (!addProperties.containsKey(k)) {
	                dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
	            }
	        } catch (Exception e) {
	        }
	    });
	    addProperties.forEach((k, v) -> {
	        try {
	        	String sclass = v.getClass().toString();
		    	if(sclass.equals("class java.util.Date")) {//动态添加的字段为date类型需要进行处理
		    		Date date = (Date) v;
		    		dynamicBean.setValue(k, date.getTime());
		    	}else {
		    		dynamicBean.setValue(k, v);
		    	}
	        } catch (Exception e) {
	        }
	    });
	    Object obj = dynamicBean.getTarget();
	    return obj;
	}
	
	public static void main(String[] args) {
		A a = new A();
		a.setAge(20);
		System.out.println("A："+JSON.toJSONString(a));
		Map<String,Object> propertiesMap = new HashMap<String,Object>();
		propertiesMap.put("name", "王");
		Object obj = ReflectUtil.getObject(a, propertiesMap);
		BeanUtils.copyProperties(a, obj);
		BeanUtils.copyProperties(obj, a);
		System.out.println("动态为A添加name之后，obj："+JSON.toJSONString(obj));
		System.out.println("动态为A添加name之后，a："+JSON.toJSONString(a));
		A a2 = (A) obj;
		System.out.println(JSON.toJSONString(a2));
	}
}

class A {
	private Integer age;
	
	public Integer getAge() {
		return age;
	}
	
	public void setAge(Integer age) {
		this.age = age;
	}
}

